 
module SandBox
  class TerminalWidget < Widget    
    
    state_defined_by :commands_log => [], :commands => []
    
    def perform
      command = context.request.params['command']
      log "> #{command}", :command
      begin
        result = eval(command || '').inspect
        log(result, :result)
      rescue
        log($!.to_s, :exception)
      end
    end
    
    
    def render
      # link in our widget's css file
      context.page.link_css(file_url('style.css'))
      
      # printout all previous commands from log
      commands_log.each do |string, className|
        e :span, :innerHTML => string, :class => className
      end
      
      #add form for typing in new commands
      cmd_input = nil
      add(DrunkenMaster::Form.new(:method => 'GET', :action => url(:perform))) do
        e :span,
            :class => 'prompt',
            :innerHTML => '&gt; '
        cmd_input =
        e :input,
            :type => 'text', 
            :name => 'command',
            :autocomplete => 'off'
        e :input,
            :type  => 'submit',
            :style => 'display:none'
      end
      
      # add script for automatic input field focus
      self.onclick =
        "document.getElementById(#{cmd_input.id}).focus()"
      e :script, 
        "document.getElementById(#{cmd_input.id}).focus();\n"+
        "document.getElementById(#{cmd_input.id}).scrollIntoView()"      
      
      # call our parent to do the rendering
      super
    end
    
  private

    def log string, className
      unless string.is_a? String
        string = string.inspect
      end
      commands_log.push [CGI.escapeHTML(string), className]
    end
  end
end